// src/context/AuthContext.jsx
import { createContext, useContext, useState, useEffect } from 'react'
import userApi from '../api/userApi'

const AuthContext = createContext()

export const useAuth = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)
  const [isAuthenticated, setIsAuthenticated] = useState(false)

  // 检查本地存储的Token
  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username')
      const userType = localStorage.getItem('userType')
      const userId = localStorage.getItem('userId')
      const employeeId = localStorage.getItem('employeeId')
      const email = localStorage.getItem('email')
      const phone = localStorage.getItem('phone')

      if (token && username) {
        try {
          // 验证Token是否有效
          const response = await userApi.validateToken()
          if (response.code === 200) {
            setUser({ 
              username, 
              userType, 
              token,
              userId: userId || response.data?.userId,
              employeeId: employeeId || response.data?.employeeId,
              email: email || response.data?.email,
              phone: phone || response.data?.phone
            })
            setIsAuthenticated(true)
          } else {
            throw new Error('Token验证失败')
          }
        } catch (error) {
          // Token无效，清除本地存储
          localStorage.removeItem('token')
          localStorage.removeItem('username')
          localStorage.removeItem('userType')
          localStorage.removeItem('rememberMe')
          localStorage.removeItem('userId')
          localStorage.removeItem('employeeId')
          localStorage.removeItem('email')
          localStorage.removeItem('phone')
          setUser(null)
          setIsAuthenticated(false)
        }
      }
      setLoading(false)
    }

    checkAuth()
  }, [])

  // 登录
  const login = async (loginData) => {
    try {
      const response = await userApi.login(loginData)
      
      if (response.code === 200 && response.data && response.data.token) {
        const userData = {
          username: response.data.username,
          userType: response.data.userType,
          token: response.data.token,
          userId: response.data.userId,
          email: response.data.email,
          phone: response.data.phone,
          employeeId: response.data.employeeId // 保存员工ID
        }
        
        setUser(userData)
        setIsAuthenticated(true)
        
        // 存储到本地
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('username', response.data.username)
        localStorage.setItem('userType', response.data.userType)
        localStorage.setItem('userId', response.data.userId)
        localStorage.setItem('employeeId', response.data.employeeId || '')
        localStorage.setItem('email', response.data.email || '')
        localStorage.setItem('phone', response.data.phone || '')
        
        return { success: true, data: userData }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      return { success: false, message: error.message || '登录失败' }
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (user?.token) {
        await userApi.logout()
      }
    } catch (error) {
      console.error('登出API调用失败:', error)
    } finally {
      // 清除本地存储和状态
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      localStorage.removeItem('userType')
      localStorage.removeItem('rememberMe')
      localStorage.removeItem('userId')
      localStorage.removeItem('employeeId')
      localStorage.removeItem('email')
      localStorage.removeItem('phone')
      setUser(null)
      setIsAuthenticated(false)
    }
  }

  // 更新用户信息
  const updateUser = (userData) => {
    setUser(prev => ({ ...prev, ...userData }))
    if (userData.username) {
      localStorage.setItem('username', userData.username)
    }
    if (userData.userType) {
      localStorage.setItem('userType', userData.userType)
    }
    if (userData.email !== undefined) {
      localStorage.setItem('email', userData.email)
    }
    if (userData.phone !== undefined) {
      localStorage.setItem('phone', userData.phone)
    }
    if (userData.employeeId !== undefined) {
      localStorage.setItem('employeeId', userData.employeeId)
    }
    if (userData.userId !== undefined) {
      localStorage.setItem('userId', userData.userId)
    }
  }

  // 检查权限
  const hasPermission = (requiredType) => {
    if (!user?.userType) return false
    
    const permissionLevels = {
      'user': 1,
      'admin': 2,
      'super_admin': 3
    }
    
    const userLevel = permissionLevels[user.userType] || 0
    const requiredLevel = permissionLevels[requiredType] || 0
    
    return userLevel >= requiredLevel
  }

  const value = {
    user,
    loading,
    isAuthenticated,
    login,
    logout,
    updateUser,
    hasPermission
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}
